package com.caocao.service.impl;

import com.caocao.domain.AccountConst;
import com.caocao.domain.mapper.ManualMapper;
import com.caocao.domain.mapper.TAvgbilldetailMapper;
import com.caocao.domain.mapper.TBilltradedeatilMapper;
import com.caocao.domain.mapper.TUserMapper;
import com.caocao.domain.model.TAvgbilldetail;
import com.caocao.domain.model.TBilltradedeatil;
import com.caocao.domain.model.TUser;
import com.caocao.domain.model.TUserExample;
import com.caocao.service.BillService;
import com.caocao.utils.DateUtils;
import com.caocao.utils.VerifyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 描述:账单相关业务接口的实现
 *
 * @Author:操文健
 * @Create Time:2017-09-16 1:19
 */
@Service
public class BillServiceImpl implements BillService {

    private static final Logger logger = LoggerFactory.getLogger(BillServiceImpl.class);

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private TBilltradedeatilMapper tBilltradedeatilMapper;

    @Autowired
    private TAvgbilldetailMapper tAvgbilldetailMapper;

    @Autowired
    private  ManualMapper manualMapper;

    /**  记录消费明细信息 */
    @Override
    @Transactional
    public boolean recordDetailAndAvgBil(TUser user, Map<String, Object> paramData)  {
        logger.info("界面记录的交易信息为:" + paramData);
        TBilltradedeatil tBilltradedeatil = new TBilltradedeatil();
        tBilltradedeatil.setBilltype((String) paramData.get("billType")); // 记账的账单类型

        String recotdDate = (String) paramData.get("recordDate");
        logger.info("当前记录账单的发生时间为：" + recotdDate );
        tBilltradedeatil.setRecorddate(DateUtils.format(recotdDate.replaceAll("/",""), "yyyyMMdd"));// 记账的日期

        BigDecimal toalMoney = new BigDecimal((String) paramData.get("totalMoney"));
        tBilltradedeatil.setTotalmoney(toalMoney);// 账单消费总金额

        String billDescripton = (String) paramData.get("description");
        tBilltradedeatil.setDescription(billDescripton);// 账单描述信息
        // 界面没有维护记账用户  系统默认记账用户即为付款用户
        tBilltradedeatil.setRecoruser(user.getId());
        tBilltradedeatil.setPayuser(user.getId());
        tBilltradedeatil.setIsclean(AccountConst.FLAG_FALSE); // 是否结清
        tBilltradedeatil.setMaketime(DateUtils.getCurrentTimestamp());
        tBilltradedeatil.setModifytime(DateUtils.getCurrentTimestamp());
        // 交易信息进行入库操作
        int restlt = tBilltradedeatilMapper.insertSelective(tBilltradedeatil);
        logger.info("明细表插入返回的结果为:" + restlt);
        logger.info("主表插入后的Id为:" + tBilltradedeatil.getId());

        // 账单均摊人员信息入库
        String costUsers = (String) paramData.get("costUsers");
        //  TODO 界面约定用户的均摊人员的取值
        String[] costArr = costUsers.split(",");
        int count = costArr.length;  // 一共需要多少人进行均摊
        BigDecimal avgMoney = toalMoney.divide(new BigDecimal(count), 3, RoundingMode.HALF_UP); // 每个人的均摊金额
        logger.info("总金额为[" + toalMoney + "],一共[" + count + "]人,每个人的均摊金额为[" + avgMoney + "]....");
        for (int i = 0 ; i < costArr.length ; i ++) {
            TAvgbilldetail tAvgbilldetail = new TAvgbilldetail();
            tAvgbilldetail.setBillId(tBilltradedeatil.getId());
            tAvgbilldetail.setUserId(Integer.parseInt(costArr[i]));// 设置每个均摊人员的Id信息
            tAvgbilldetail.setAvgmoney(avgMoney);
            tAvgbilldetail.setMaketime(DateUtils.getCurrentTimestamp());
            tAvgbilldetail.setModifytime(DateUtils.getCurrentTimestamp());
            tAvgbilldetailMapper.insertSelective(tAvgbilldetail);
        }

        return true;
    }

    /**  根据用户Id查询消费明细信息 */
    @Override
    public Map<String, Object> queryBillDetailsByUser(Integer userId) {
        logger.info("开始查询消费明细信息...");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 查询账单总金额
        BigDecimal allMoney = manualMapper.getAllMoney();
        resultMap.put("totalMoney", allMoney);
        // 查询记录消费明细信息
        List<Map<String, Object>> recoedDetail = manualMapper.queryBillDetailByUserId(userId);
        resultMap.put("recoedDetail", recoedDetail);

        return resultMap;
    }

    /**  截止目前每个人的消费情况*/
    @Override
    public List<Map<String, Object>> spengRatioForEveryOne() {
        // 查询所有的有效客户信息
        TUserExample tUserExample = new TUserExample();
        tUserExample.createCriteria().andIsvalidEqualTo(AccountConst.FLAG_TEUE);
        List<TUser> userList = tUserMapper.selectByExample(tUserExample);
        // 创建返回的Data集合信息
        List<Map<String, Object>> resultMap = new ArrayList<Map<String, Object>>();
         // 循环迭代有效的用户信息进行查询相应的结果信息进行数据装载
        for (TUser tUser : userList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", tUser.getId());
            map.put("userCode", tUser.getUsercode());
            map.put("userName", tUser.getUsername());

            BigDecimal allAvgMoney = manualMapper.getAvgMenryForUserId(tUser.getId());
            BigDecimal allPaymoney = manualMapper.getPayMoneyForUserId(tUser.getId());

            BigDecimal money = (VerifyUtil.isEmpty(allAvgMoney) ? new BigDecimal("0") : allAvgMoney ).subtract(VerifyUtil.isEmpty(allPaymoney) ? new BigDecimal("0")  : allPaymoney);

            map.put("money", money);
            resultMap.add(map);
        }
        return resultMap;
    }
    /**  截止目前的消费比例 */
    @Override
    public List<Map<String, Object>> billTypeRatio() {
        // 界面返回结果使用集合
        List<Map<String, Object>> resultMap = new ArrayList<Map<String, Object>>();
        // 查询账单总金额
        BigDecimal allMoney = manualMapper.getAllMoney();
        logger.info("未结清的账单消费总金额为：" + allMoney);
        // 查询每个类型对应的金额信息
        List<Map<String, Object>> billTypeList = manualMapper.getAllMoneyForBillType();
        logger.info("查询的每种消费类型对应的数据为：" + billTypeList);
        for (Map<String, Object> billmap : billTypeList) {
            //logger.info("循环到当前的数据信息为：" +billmap );
            Map<String, Object> billTypeTemp = new HashMap<String, Object>();
            billTypeTemp.put("billType", billmap.get("billType"));
            billTypeTemp.put("billTypeName", billmap.get("billTypeName"));
            billTypeTemp.put("typeMoney", ((BigDecimal) billmap.get("typeMoney")).divide(allMoney, 3));
            resultMap.add(billTypeTemp);
        }
        return resultMap;
    }
}
